<template>
  <div
      v-loading="loading"
      v-empty="nopermission"
      class="rc-cont"
      xs-empty-icon="nopermission"
      xs-empty-text="暂无权限">
    <flexbox
        v-if="!isSeas"
        class="rc-head"
        direction="row-reverse">
      <el-button
          v-if="contactsSave"
          class="xr-btn--orange rc-head-item"
          icon="el-icon-plus"
          type="primary"
          @click="createClick">新建联系人
      </el-button>
      <el-button
          v-if="canRelation"
          class="rc-head-item"
          type="primary"
          @click="unRelevanceHandleClick">解除关联
      </el-button>
      <el-popover v-if="canRelation" v-model:visible="showRelativeView"
                  placement="bottom" width="700" popper-class="no-padding-popover"
                  trigger="click" style="margin-right: 20px;">
        <crm-relative
            ref="crmrelative"
            v-model="showRelativeView"
            :show="showRelativeView"
            :radio="false"
            :action="{ type: 'condition', data: { moduleType: 'customer', customerId: customerId } }"
            :selected-data="{ 'contacts': list }"
            crm-type="contacts"
            @close="showRelativeView = false"
            @changeCheckout="checkRelativeInfos"/>
        <el-button
            slot="reference"
            class="rc-head-item"
            style="margin-right: 0;"
            type="primary"
            @click="showRelativeView = true">关联
        </el-button>
      </el-popover>

    </flexbox>
    <el-table
        v-show="fieldList.length > 0"
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        stripe
        style="width: 100%;border: 1px solid #E6E6E6;"
        @row-click="handleRowClick"
        @selection-change="selectionList = $event">
      <el-table-column
          v-if="canRelation"
          show-overflow-tooltip
          type="selection"
          align="center"
          width="55"/>
      <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          show-overflow-tooltip/>
      <el-table-column
          label="操作"
          width="100">
        <template #default="scope">
          <!--        <template slot-scope="scope">-->
          <flexbox justify="center">
            <span
                v-if="contactsId == scope.row.contactsId"
                class="chief">
            <i class="wk wk-success"/>首要联系人</span>
            <el-button v-else-if="!isSeas" class="set-chief-btn" link
                       @click="setChieflyContacts(scope)">
              设为首要联系人
            </el-button>
          </flexbox>
        </template>
      </el-table-column>
    </el-table>
    <c-r-m-full-screen-detail
        v-model:visible="showFullDetail"
        :id="detailId"
        crm-type="contacts"
        @handle="detailHandle"/>
    <c-r-m-all-create
        v-if="isCreate"
        :action="createActionInfo"
        crm-type="contacts"
        @save-success="createSaveSuccess"
        @close="isCreate=false"/>
  </div>
</template>


<script setup>
import CRMAllCreate from '../SzCrud/CRMAllCreate.vue'
import {
  crmCustomerQueryContactsAPI,
  crmCustomerSetContactsAPI
} from '/src/api/crm/customer.js'
import {
  crmBusinessQueryContactsAPI,
  crmBusinessRelateContactsAPI,
  crmBusinessUnrelateContactsAPI,
  crmBusinessSetContactsAPI
} from '/src/api/crm/business.js'
import CrmRelative from '/src/components/CreateCom/CrmRelative.vue'
import {getPermissionByKey} from '/src/utils/index.js'
import {getCurrentInstance} from "vue";
import CRMFullScreenDetail from "components/CRMFullScreenDetail.vue"
import {ref, watch, computed, nextTick, onMounted} from "vue"
import {ElMessage, ElMessageBox} from "element-plus"

// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus


defineOptions({
  name: 'RelativeContacts', // 相关联系人列表  可能再很多地方展示 放到客户管理目录下
})

const emits = defineEmits(['update:contactsId'])

const props = defineProps({
  // 模块ID
  id: [String, Number],
  // 首要联系人ID
  contactsId: [String, Number],
  // 客户类型
  crmType: {
    type: String,
    default: ''
  },
  // 是公海 默认是客户
  isSeas: {
    type: Boolean,
    default: false
  },
  // 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  }
})


const loading = ref(false)
const nopermission = ref(false)
const list = ref([])
const fieldList = ref([])
const tableHeight = ref('400px')
const showFullDetail = ref(false)
// 控制新建
const isCreate = ref(false)
// 查看全屏联系人详情的 ID
const detailId = ref('')
// 创建的相关信息
const createActionInfo = ref({type: 'relative', crmType: props.crmType, data: {}})
// 关联的逻辑
const showRelativeView = ref(false)
const selectionList = ref([])


const rootTabs = inject('rootTabs')

// 联系人下客户id获取关联商机
const customerId = computed(() => {
  return props.detail.customerId
})
// 是否能关联
const canRelation = computed(() => {
  return props.crmType == 'business'
})
const contactsSave = computed(() => {
  return !!getPermissionByKey('crm.contacts.save')
})

watch(() => props.id, (val) => {
  list.value = []
  getDetail()
})

watch(() => rootTabs.currentName, (val) => {
  if (val === 'RelativeContacts') {
    getDetail(false)
  }
})

onMounted(() => {
  getDetail()
})


/**
 * 关联的数据
 */
function checkRelativeInfos(data) {
  if (data.data.length > 0) {
    const params = {businessId: props.id}
    params.contactsIds = data.data
        .map(item => {
          return item.contactsId
        })
    crmBusinessRelateContactsAPI(params)
        .then(res => {
          getDetail()
          ElMessage.success({message: '操作成功'})
        })
        .catch(() => {
        })
  }
}

/**
 * 取消关联
 */
function unRelevanceHandleClick() {
  if (selectionList.value.length == 0) {
    ElMessage.error({message: '请先勾选数据'})
  } else {
    ElMessageBox.confirm('确认取消关联?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          const params = {businessId: props.id}
          params.contactsIds = selectionList.value
              .map(item => {
                return item.contactsId
              })
          crmBusinessUnrelateContactsAPI(params)
              .then(res => {
                getDetail()
                ElMessage.success({message: '操作成功'})
              })
              .catch(() => {
              })
        })
        .catch(() => {
        })
  }
}

/**
 * 表头数据
 */
function getFieldList() {
  fieldList.value.push({
    prop: 'name',
    width: '200',
    label: '姓名'
  })
  fieldList.value.push({prop: 'mobile', width: '200', label: '手机'})
  fieldList.value.push({prop: 'post', width: '200', label: '职务'})
}

/**
 * 获取数据
 */
function getDetail(loading = true) {
  loading.value = loading
  const request = {
    customer: crmCustomerQueryContactsAPI,
    business: crmBusinessQueryContactsAPI
  }[props.crmType]
  const params = {pageType: 0}
  params[props.crmType + 'Id'] = props.id
  request(params).then(res => {
    if (fieldList.value.length == 0) {
      getFieldList()
    }
    nopermission.value = false
    loading.value = false
    list.value = res.data.data.list
  }).catch(data => {
    if (data.code == 102) {
      nopermission.value = true
    }
    loading.value = false
  })
}

/**
 * 当某一行被点击时会触发该事件
 */
function handleRowClick(row, column, event) {
  if (column.property == 'name') {
    detailId.value = row.contactsId
    showFullDetail.value = true
  }
}

/**
 * 通过回调控制class
 */
function cellClassName({row, column, rowIndex, columnIndex}) {
  if (column.property === 'name') {
    return 'can-visit--underline'
  } else {
    return ''
  }
}

/**
 * 新建
 */
function createClick() {
  //  客户 下新建联系人
  if (props.crmType == 'customer') {
    createActionInfo.value.data['customer'] = props.detail
  } else if (props.crmType == 'business') {
    createActionInfo.value.data['customer'] = props.detail
    createActionInfo.value.relativeData = {
      businessId: props.detail.businessId
    }
  }
  isCreate.value = true
}

function createSaveSuccess() {
  if (canRelation.value) {
    cxt.refs.crmrelative.refreshList()
  } else {
    bus.emit('crm-tab-num-update')
    getDetail()
  }
}

/**
 * 设置首要联系人
 */
function setChieflyContacts(data) {
  const request = {
    customer: crmCustomerSetContactsAPI,
    business: crmBusinessSetContactsAPI
  }[props.crmType]

  const params = {contactsId: data.row.contactsId}
  params[props.crmType + 'Id'] = props.id
  loading.value = true
  request(params)
      .then(res => {
        ElMessage.success({message: '操作成功'})
        emits('update:contactsId', data.row.contactsId)
        loading.value = false
      })
      .catch(data => {
        loading.value = false
      })
}

/**
 * 详情操作
 */
function detailHandle(data) {
  if (data.type === 'delete') {
    getDetail()
    nextTick(() => {
      bus.emit('crm-tab-num-update')
    })
  }
}


</script>

<script type="text/javascript">
export default {
  components: {
    // CRMAllCreate,
    // CrmRelative
  },
  mixins: [],
  props: {},
  data() {
    return {}
  },
  // inject: ['rootTabs'],
  computed: {},
  watch: {},
  mounted() {
  },
  methods: {}
}
</script>
<style lang="scss" scoped>
@import '../../styles/relativecrm';

.set-chief-btn {
  font-size: 12px;
  padding: 4px 12px;
}

.chief {
  font-size: 12px;
  color: #333;

  i {
    font-size: 14px;
    color: #389e0b;
    margin-right: 3px;
  }
}
</style>
